package com.genexususa.eo.bing.connection;

import com.genexususa.eo.bing.CampaignManagementServiceClasses.*;
import com.genexususa.eo.bing.data.GxException;
import com.genexususa.eo.bing.data.GxItemException;
import com.genexususa.eo.bing.data.Info;
import com.genexususa.eo.bing.data.Util;
import com.genexususa.eo.bing.data.results.*;
import com.genexususa.eo.bing.data.requests.GxAdsAdGroupRequest;
import com.genexususa.eo.bing.data.util.BingTextAd;
import com.genexususa.eo.bing.data.wsSubclasses.GxAdsRequest;
import com.genexususa.eo.bing.data.wsSubclasses.GxMobileAd;
import com.genexususa.eo.bing.data.wsSubclasses.GxTextAd;
import com.genexususa.eo.google.data.*;
import com.genexususa.eo.google.data.Error;
import org.apache.axis.AxisFault;
import org.xml.sax.SAXException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.rpc.ServiceException;
import java.io.IOException;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;

public class AdManager {
    public AdManager() {
    }

    public String addAds(long customerAccountId, String adsRequestsXML) {
        ICampaignManagementService campaignManagement = null;
        CampaignManagementServiceLocator campaignServiceLocator = null;
        BasicHttpBinding_ICampaignManagementServiceStub stub = null;
        AddAdsRequest addAdsRequest = null;
        AddAdsResponse addAdsResponse = null;

        GA_Result result = new GA_Result();

        //GxElementsResults result = null;
        Util util = new Util();
        GxAdsRequest[] adsRequests = null;
        GxAdsAdGroupRequest adsAdGroupRequest = null;
        try {
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("campaignNamespace");
            String url = properties.get("campaignURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            campaignServiceLocator = new CampaignManagementServiceLocator();
            campaignServiceLocator.setBasicHttpBinding_ICampaignManagementServiceEndpointAddress(url);
            campaignManagement = campaignServiceLocator.getBasicHttpBinding_ICampaignManagementService(); // ServiceException
            stub = (BasicHttpBinding_ICampaignManagementServiceStub) campaignManagement;

            // Set header parameters
            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);


            // Parse adsRequests from XML
            adsRequests = util.adsRequestsFromXML(adsRequestsXML); // IllegalArgumentException, GxException, ParserConfigurationException, SAXException, IOException
            if (adsRequests.length == 0) {
                throw new GxItemException("No AdsRequests were found");
            }

            /*for (int i=0; i<adsRequests.length; i++) {
                result.addResult(i, new GxElementsCampaignsResult(adsRequests[i].getAdsAdGroupRequests().length));
                for (int j=0; j<adsRequests[i].getAdsAdGroupRequests().length; j++) {
                    result.getElementsCampaignsResultCollection()[i].addResult(j, new GxElementsAdGroupsResult());
                }
            }
            */
            for (int k=0; k<adsRequests.length; k++) {
                GxAdsRequest adRequest = adsRequests[k];

                //result.getElementsCampaignsResultCollection()[k].setGxCampaignId(adsRequests[k].getGxCampaignId());
                //result.getElementsCampaignsResultCollection()[k].setBingCampaignId(adsRequests[k].getBingCampaignId());
                for (int j=0; j<adRequest.getAdsAdGroupRequests().length; j++) {
                    adsAdGroupRequest = adRequest.getAdsAdGroupRequests()[j];

                    // Set body parameters
                    addAdsRequest = new AddAdsRequest();
                    addAdsRequest.setAdGroupId(adsAdGroupRequest.getBingAdGroupId());
                    //addAdsRequest.setAds(adsAdGroupRequest.getAds());

                    try {

                        Ad[] allAds = adsAdGroupRequest.getAds();
                        Ad[] chunkedAds = null;
                        // max element limit = 1000
                        int chunks = (int)Math.ceil(allAds.length / 1000.0);
                        if (chunks <= 1){
                            addAdsRequest.setAds(allAds);

                            addAdsResponse = campaignManagement.addAds(addAdsRequest); // RemoteException, EditorialApiFaultDetail, AdApiFaultDetail

                            for (int i=0; i<addAdsResponse.getAdIds().length; i++) {
                                GA_ResultItem resultItem = new GA_ResultItem(addAdsResponse.getPartialErrors(), i);

                                resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                                resultItem.CampaignId = adRequest.getBingCampaignId();
                                resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                                resultItem.AdGroupId = adsAdGroupRequest.getBingAdGroupId();
                                if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                    resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                                    resultItem.AdId = addAdsResponse.getAdIds()[i];
                                } else {
                                    resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                                    resultItem.AdId = addAdsResponse.getAdIds()[i];
                                }

                                result.Items.add(resultItem);
                            }
                        }else if(chunks > 1){
                            int counter = 1;
                            int index = 0;
                            int chunkItems = 1000;
                            while (counter <= chunks){
                                if(counter == chunks){
                                    chunkItems = allAds.length - index;
                                }

                                chunkedAds = new Ad[chunkItems];
                                for(int i = 0; i < chunkItems ; i++){
                                    chunkedAds[i] = allAds[index];
                                    index+=1;
                                }
                                index = counter * 1000;
                                counter++;

                                addAdsRequest.setAds(chunkedAds);

                                addAdsResponse = campaignManagement.addAds(addAdsRequest); // RemoteException, EditorialApiFaultDetail, AdApiFaultDetail

                                for (int i=0; i<addAdsResponse.getAdIds().length; i++) {
                                    GA_ResultItem resultItem = new GA_ResultItem(addAdsResponse.getPartialErrors(), i);

                                    resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                                    resultItem.CampaignId = adRequest.getBingCampaignId();
                                    resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                                    resultItem.AdGroupId = adsAdGroupRequest.getBingAdGroupId();
                                    if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                        resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                                        resultItem.AdId = addAdsResponse.getAdIds()[i];
                                    } else {
                                        resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                                        resultItem.AdId = addAdsResponse.getAdIds()[i];
                                    }

                                    result.Items.add(resultItem);
                                }
                            }
                        }
                    } catch (EditorialApiFaultDetail fault) { // IN CALL
                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(fault, i);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        }
                    } catch (AdApiFaultDetail fault) { // IN CALL
                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(fault);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        }
                    } catch (AxisFault e) { // IN CALL

                        ArrayList<BingTextAd> textAds = getAdsByAdGroupId(customerAccountId, adsAdGroupRequest.getBingAdGroupId());


                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {



                            GA_ResultItem resultItem = new GA_ResultItem(e);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();

                                GxTextAd gxTextAd = ((GxTextAd) adsAdGroupRequest.getAds()[i]);
                                Long isCreated = isCreatedAd(textAds, gxTextAd);
                                if (isCreated != 0L){
                                    resultItem.HasError = false;
                                    resultItem.Errors = null;
                                    resultItem.AdId = isCreated;
                                    resultItem.AdGroupId = adsAdGroupRequest.getBingAdGroupId();
                                }
                                else{
                                    resultItem.HasError = true;
                                    resultItem.Errors = new ErrorsStruct();
                                    resultItem.Errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
                                    com.genexususa.eo.google.data.Error error = new com.genexususa.eo.google.data.Error();

                                    error.ErrorString = "The specified Text Ad has one or several errors. Please check Title, Description and URLs.";
                                    resultItem.Errors.Errors.add(error);

                                }
                                result.Items.add(resultItem);
                            }
                        }
                    } catch (RemoteException e) { // IN CALL
                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(e);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        }
                    }
                }
            }
        } catch (GxException e) { // BEFORE CALL
            result.Items.add(new GA_ResultItem(e));
        } catch (Exception e) { // BEFORE CALL
            result.Items.add(new GA_ResultItem(e));
        }

        String returnMessage = null;
        // GxElementsResults -> XML
        try {
            JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class); // JAXBException

            Marshaller marshallerObj = contextObj.createMarshaller(); // JAXBException
            marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // PropertyException

            StringWriter sw = new StringWriter();

            marshallerObj.marshal(result, sw); // JAXBException
            returnMessage = sw.getBuffer().toString();
        }  catch (PropertyException e) { // AFTER CALL
            returnMessage = util.getPropertyExceptionMessage(e);
        } catch (JAXBException e) { // AFTER CALL
            returnMessage = util.getJAXBExceptionMessage(e);
        }
        return returnMessage;
    }

    public String updateAds(long customerAccountId, String adsRequestsXML) {
        ICampaignManagementService campaignManagement = null;
        CampaignManagementServiceLocator campaignServiceLocator = null;
        BasicHttpBinding_ICampaignManagementServiceStub stub = null;
        UpdateAdsRequest updateAdsRequest = null;
        //GxElementsResults result = null;
        GA_Result result = new GA_Result();
        Util util = new Util();
        GxAdsRequest[] adsRequests = null;
        GxAdsAdGroupRequest adsAdGroupRequest = null;
        try {
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("campaignNamespace");
            String url = properties.get("campaignURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            campaignServiceLocator = new CampaignManagementServiceLocator();
            campaignServiceLocator.setBasicHttpBinding_ICampaignManagementServiceEndpointAddress(url);
            campaignManagement = campaignServiceLocator.getBasicHttpBinding_ICampaignManagementService(); // ServiceException
            stub = (BasicHttpBinding_ICampaignManagementServiceStub) campaignManagement;

            // Set header parameters
            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            // Parse adsRequests from XML
            adsRequests = util.adsRequestsFromXML(adsRequestsXML); // IllegalArgumentException, GxException, ParserConfigurationException, SAXException, IOException
            if (adsRequests.length == 0) {
                throw new GxItemException("No AdsRequests were found");
            }

            /*result = new GxElementsResults(adsRequests.length);
            for (int i=0; i<adsRequests.length; i++) {
                result.addResult(i, new GxElementsCampaignsResult(adsRequests[i].getAdsAdGroupRequests().length));
                for (int j=0; j<adsRequests[i].getAdsAdGroupRequests().length; j++) {
                    result.getElementsCampaignsResultCollection()[i].addResult(j, new GxElementsAdGroupsResult());
                }
            }
            */
            for (int k=0; k<adsRequests.length; k++) {
                GxAdsRequest adRequest = adsRequests[k];

                //result.getElementsCampaignsResultCollection()[k].setGxCampaignId(adsRequests[k].getGxCampaignId());
                //result.getElementsCampaignsResultCollection()[k].setBingCampaignId(adsRequests[k].getBingCampaignId());
                for (int j=0; j<adRequest.getAdsAdGroupRequests().length; j++) {
                    adsAdGroupRequest = adRequest.getAdsAdGroupRequests()[j];

                    // Set body parameters
                    updateAdsRequest = new UpdateAdsRequest();
                    updateAdsRequest.setAdGroupId(adsAdGroupRequest.getBingAdGroupId());
                    updateAdsRequest.setAds(adsAdGroupRequest.getAds());

                    try {
                        // Call WS
                        UpdateAdsResponse response = campaignManagement.updateAds(updateAdsRequest); // RemoteException, EditorialApiFaultDetail, AdApiFaultDetail

                        // Call succeeded with no errors

                        // Create the return object

                        for (int i=0; i<adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(response.getPartialErrors(), i);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.CampaignId = adRequest.getBingCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            resultItem.AdGroupId = adsAdGroupRequest.getBingAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                                resultItem.AdId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                                resultItem.AdId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getId();
                            }

                            result.Items.add(resultItem);
                        }
                    } catch (EditorialApiFaultDetail fault) { // IN CALL
                        for (int i=0; i<adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem =  new GA_ResultItem(fault, i);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        }
                    } catch (AdApiFaultDetail fault) { // IN CALL


                        ArrayList<BingTextAd> textAds = getAdsByAdGroupId(customerAccountId, adsAdGroupRequest.getBingAdGroupId());


                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {



                            GA_ResultItem resultItem = new GA_ResultItem(fault);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();

                                GxTextAd gxTextAd = ((GxTextAd) adsAdGroupRequest.getAds()[i]);
                                Long isCreated = isCreatedAd(textAds, gxTextAd);
                                if (isCreated != 0L){
                                    resultItem.HasError = false;
                                    resultItem.Errors = null;
                                    resultItem.AdId = isCreated;
                                    resultItem.AdGroupId = adsAdGroupRequest.getBingAdGroupId();
                                }
                                else{
                                    resultItem.HasError = true;
                                    resultItem.Errors = new ErrorsStruct();
                                    resultItem.Errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
                                    com.genexususa.eo.google.data.Error error = new com.genexususa.eo.google.data.Error();

                                    error.ErrorString = "The specified Text Ad has one or several errors. Please check Title, Description and URLs.";
                                    resultItem.Errors.Errors.add(error);

                                }
                                result.Items.add(resultItem);
                            }
                        }


                        /*for (int i=0; i<adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(fault);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId =  ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId =  ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        } */
                    } catch (RemoteException e) { // IN CALL
                        for (int i=0; i<adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(e);

                            resultItem.SubCampaignGxId = adRequest.getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        }
                    }
                }
            }
        } catch (GxException e) { // BEFORE CALL
            result.Items.add(new GA_ResultItem(e));
        } catch (Exception e) { // BEFORE CALL
            result.Items.add(new GA_ResultItem(e));
        }

        String returnMessage = null;
        // GxElementsResults -> XML
        try {
            JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class); // JAXBException

            Marshaller marshallerObj = contextObj.createMarshaller(); // JAXBException
            marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // PropertyException

            StringWriter sw = new StringWriter();

            marshallerObj.marshal(result, sw); // JAXBException
            returnMessage = sw.getBuffer().toString();
        }  catch (PropertyException e) { // AFTER CALL
            returnMessage = util.getPropertyExceptionMessage(e);
        } catch (JAXBException e) { // AFTER CALL
            returnMessage = util.getJAXBExceptionMessage(e);
        }
        return returnMessage;
    }

    public String deleteAds(long customerAccountId, String adsRequestsXML) {
        ICampaignManagementService campaignManagement = null;
        CampaignManagementServiceLocator campaignServiceLocator = null;
        BasicHttpBinding_ICampaignManagementServiceStub stub = null;
        DeleteAdsRequest deleteAdsRequest = null;
        //GxElementsResults result = null;
        GA_Result result = new GA_Result();
        Util util = new Util();
        GxAdsRequest[] adsRequests = null;
        GxAdsAdGroupRequest adsAdGroupRequest = null;
        try {
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("campaignNamespace");
            String url = properties.get("campaignURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            campaignServiceLocator = new CampaignManagementServiceLocator();
            campaignServiceLocator.setBasicHttpBinding_ICampaignManagementServiceEndpointAddress(url);
            campaignManagement = campaignServiceLocator.getBasicHttpBinding_ICampaignManagementService(); // ServiceException
            stub = (BasicHttpBinding_ICampaignManagementServiceStub) campaignManagement;

            // Set header parameters
            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);
            stub.setHeader(namespace, "ApplicationToken", applicationToken);

            // Parse adRequests from XML
            adsRequests = util.adsRequestsFromXML(adsRequestsXML); // IllegalArgumentException, GxException, ParserConfigurationException, SAXException, IOException
            if (adsRequests.length == 0) {
                throw new GxItemException("No AdsRequests were found");
            }

            for (int k=0; k<adsRequests.length; k++) {

                /*result.getElementsCampaignsResultCollection()[k].setGxCampaignId(adsRequests[k].getGxCampaignId());
                result.getElementsCampaignsResultCollection()[k].setBingCampaignId(adsRequests[k].getBingCampaignId());*/
                for (int j=0; j<adsRequests[k].getAdsAdGroupRequests().length; j++) {
                    adsAdGroupRequest = adsRequests[k].getAdsAdGroupRequests()[j];

                    // Set body parameters
                    deleteAdsRequest = new DeleteAdsRequest();
                    deleteAdsRequest.setAdGroupId(adsAdGroupRequest.getBingAdGroupId());
                    long[] adIds = new long[adsAdGroupRequest.getAds().length];
                    for (int i=0; i<adIds.length; i++) {
                        if (adsAdGroupRequest.getAds()[i].getId() == null) {
                            adIds[i] = -1;
                        } else {
                            adIds[i] = adsAdGroupRequest.getAds()[i].getId();
                        }
                    }
                    deleteAdsRequest.setAdIds(adIds);

                    try {
                        // Call WS
                        DeleteAdsResponse response = campaignManagement.deleteAds(deleteAdsRequest); // RemoteException, ApiFaultDetail, AdApiFaultDetail

                        // Call succeeded with no errors

                        // Create the return object

                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem =  new GA_ResultItem(response.getPartialErrors(), i);

                            resultItem.SubCampaignGxId = adsRequests[k].getGxCampaignId();
                            resultItem.CampaignId = adsRequests[k].getBingCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            resultItem.AdGroupId =  adsAdGroupRequest.getBingAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                                resultItem.AdId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                                resultItem.AdId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getId();
                            }

                            result.Items.add(resultItem);
                        }
                    } catch (ApiFaultDetail fault) { // IN CALL
                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(fault, i);

                            resultItem.SubCampaignGxId = adsRequests[k].getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        }
                    } catch (AdApiFaultDetail fault) { // IN CALL
                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(fault);

                            resultItem.SubCampaignGxId = adsRequests[k].getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();

                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        }
                    } catch (RemoteException e) { // IN CALL
                        for (int i=0; i< adsAdGroupRequest.getAds().length; i++) {
                            GA_ResultItem resultItem = new GA_ResultItem(e);

                            resultItem.SubCampaignGxId = adsRequests[k].getGxCampaignId();
                            resultItem.AdGroupGxId = adsAdGroupRequest.getGxAdGroupId();
                            if (adsAdGroupRequest.getAds()[i] instanceof GxMobileAd) {
                                resultItem.AdGxId = ((GxMobileAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            } else {
                                resultItem.AdGxId = ((GxTextAd) adsAdGroupRequest.getAds()[i]).getGxId();
                            }

                            result.Items.add(resultItem);
                        }
                    }
                }
            }
        } catch (GxException e) { // BEFORE CALL
            result.Items.add(new GA_ResultItem(e));
        } catch (Exception e) { // BEFORE CALL
            result.Items.add(new GA_ResultItem(e));
        }

        String returnMessage = null;
        // GxElementsResults -> XML
        try {
            JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class); // JAXBException

            Marshaller marshallerObj = contextObj.createMarshaller(); // JAXBException
            marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // PropertyException

            StringWriter sw = new StringWriter();

            marshallerObj.marshal(result, sw); // JAXBException
            returnMessage = sw.getBuffer().toString();
        }  catch (PropertyException e) { // AFTER CALL
            returnMessage = util.getPropertyExceptionMessage(e);
        } catch (JAXBException e) { // AFTER CALL
            returnMessage = util.getJAXBExceptionMessage(e);
        }
        return returnMessage;
    }

    public ArrayList<BingTextAd> getAdsByAdGroupId(long customerAccountId, long adGroupId){
        BasicHttpBinding_ICampaignManagementServiceStub stub = null;
        ArrayList<BingTextAd> bingTextAds = new ArrayList<BingTextAd>();
        try{
            HashMap<String, String> properties = Info.getBingProperties();
            String namespace = properties.get("campaignNamespace");
            String url = properties.get("campaignURL");
            String userName = properties.get("username");
            String password = properties.get("password");
            String developerToken = properties.get("developerToken");
            String customerId = properties.get("customerId");
            String applicationToken = properties.get("applicationToken");

            CampaignManagementServiceLocator locator = new CampaignManagementServiceLocator();
            locator.setBasicHttpBinding_ICampaignManagementServiceEndpointAddress(url);
            namespace = locator.getServiceName().getNamespaceURI();
            stub = (BasicHttpBinding_ICampaignManagementServiceStub) locator.getBasicHttpBinding_ICampaignManagementService();

            stub.clearHeaders();

            stub.setHeader(namespace, "UserName", userName);
            stub.setHeader(namespace, "Password", password);
            stub.setHeader(namespace, "DeveloperToken", developerToken);
            stub.setHeader(namespace, "CustomerId", customerId);
            stub.setHeader(namespace, "CustomerAccountId", customerAccountId);

            GetAdsByAdGroupIdRequest request = new GetAdsByAdGroupIdRequest();
            request.setAdGroupId(adGroupId);

            GetAdsByAdGroupIdResponse response = stub.getAdsByAdGroupId(request);

            Ad[] ads = response.getAds();

            bingTextAds = new ArrayList<BingTextAd>();

            for (Ad ad : ads){


                if (ad instanceof TextAd){
                    TextAd textAd = (TextAd)ad;

                    BingTextAd bingTextAd = new BingTextAd();
                    bingTextAd.DestinationUrl = textAd.getDestinationUrl();
                    bingTextAd.Id = textAd.getId();
                    bingTextAd.DisplayUrl = textAd.getDisplayUrl();
                    bingTextAd.Text = textAd.getText();
                    bingTextAd.Title = textAd.getTitle();

                    bingTextAds.add(bingTextAd);
                }
            }

            return bingTextAds;

        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ServiceException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return bingTextAds;
    }

    private boolean compareTextAds(BingTextAd bingTextAd, GxTextAd gxTextAd){

        return (bingTextAd.Title.equalsIgnoreCase(gxTextAd.getTitle()) &&
                bingTextAd.Text.equalsIgnoreCase(gxTextAd.getText())/* &&
                bingTextAd.DisplayUrl.equalsIgnoreCase(gxTextAd.getDisplayUrl()) &&
                bingTextAd.DestinationUrl.equalsIgnoreCase(gxTextAd.getDestinationUrl())*/);
    }

    private Long isCreatedAd(ArrayList<BingTextAd> ads, GxTextAd gxTextAd){
        Long isCreated = 0L;
        for (BingTextAd ad : ads){
            if (compareTextAds(ad, gxTextAd)){
                isCreated = ad.Id;
                break;
            }
        }
        return isCreated;
    }
}
